<template>
	<div class="admin">
		<el-card class="!border-none" shadow="never" id="headerH">
			<el-form class="mb-[-16px]" :model="formData" inline>
				<el-form-item label="单据信息">
					<el-input v-model="formData.order_no" @keyup.enter="resetPage" class="w-40" size="small"
						clearable placeholder="请输入单据信息"/>
				</el-form-item>
				<!-- <el-form-item label="货单单号">
					<el-input v-model="formData.delivery_no" @keyup.enter="resetPage" class="w-40" size="small"
						clearable />
				</el-form-item> -->
				<el-form-item label="单据类型">
					<el-select class="w-40" v-model="formData.type" @keyup.enter="resetPage" size="small" clearable>
						<el-option v-for="(item, index) in options.listtype" :key="index" :label="item.title"
							:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="出库仓库">
					<el-select class="w-40" v-model="formData.outbound_warehouse_id" @keyup.enter="resetPage"
						size="small" clearable>
						<el-option v-for="(item, index) in options.listColumn" :key="index" :label="item.title"
							:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="入库仓库">
					<el-select class="w-40" v-model="formData.warehouse_id" @keyup.enter="resetPage" size="small"
						clearable>
						<el-option v-for="(item, index) in options.listColumn" :key="index" :label="item.title"
							:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="单据日期">
					<el-date-picker class="w-40" v-model="date" @keyup.enter="resetPage" type="daterange"
						format="YYYY/MM/DD" value-format="YYYY-MM-DD" range-separator="至" start-placeholder="起始时间"
						end-placeholder="结束时间" size="small" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="resetPage" size="small">查询</el-button>
					<el-button @click="onresetParams" size="small">重置</el-button>
				</el-form-item>
			</el-form>
		</el-card>
		<el-card v-loading="pager.loading" class="mt-2 !border-none" shadow="never">
			<el-button v-if="options.useJurisdictionr" v-perms="['order.order/add']" type="primary" @click="handleAddr"
				size="small">
				<template #icon>
					<icon name="el-icon-Plus" />
				</template>
				新增入库单
			</el-button>
			<el-button v-perms="['order.order/add']" v-if="options.useJurisdiction" size="small" type="primary"
				@click="handleAdd">
				<template #icon>
					<icon name="el-icon-Plus" />
				</template>
				新增调拨单
			</el-button>
			<div style="margin-top: 3px;">
				<mtable :data="pager.lists" :type="typeTable" :list="options.tableTile" :bill="true" :operation="true"
					:tableheight="tableheight" @handleAdds="handleAdds">
					<template #tool="{item}">
						<el-table-column v-if="item.display==1" sortable :label="item.name" show-overflow-tooltip
							:prop="item.value" :width="item.width">
							<template #default="{ row }">
								<div v-if="item.name=='类型'">
									<el-button v-if="row.type==20" size="small" color="#38ddcd" plain>{{row.type_name}}
									</el-button>
									<el-button v-if="row.type==10" size="small" color="#ae75ef" plain>{{row.type_name}}
									</el-button>
								</div>
								<div v-if="item.name=='状态'">
									<el-button v-if="row.status_name=='待入库'" size="small" color="#E6A23C" plain>
										{{row.status_name}}
									</el-button>
									<el-button v-if="row.status_name=='已作废'" size="small" color="#c8cacc" plain>
										{{row.status_name}}
									</el-button>
									<el-button v-if="row.status_name=='已入库'" size="small" color="#67C23A" plain>
										{{row.status_name}}
									</el-button>
									<el-button v-if="row.status_name=='待出库'" size="small" color="#58c1ee" plain>
										{{row.status_name}}
									</el-button>
									<el-button v-if="row.status_name=='已驳回'" size="small" color="#F56C6C" plain>
										{{row.status_name}}
									</el-button>
									<el-button v-if="row.status_name=='待审核'" size="small" color="#ff557f" plain>
										{{row.status_name}}
									</el-button>
								</div>
								<div v-if="item.name=='照片'">
									<div class="demo-image__preview">
										<el-image class="imgTable" :src="row.delivery_image[0]?.url"
											:preview-src-list="imgData(row.delivery_image)" :initial-index="0">
											<template #error>
												<div class="image-slot"></div>
											</template>
										</el-image>
									</div>
								</div>
							</template>
						</el-table-column>
					</template>
					<template #operation="{row,val}">
						<el-button type="primary" link @click="handleEdit(val)">
							<!-- <el-badge v-if="row" is-dot class="item"></el-badge> -->
							<span v-if="row" class="chankan">查看
							<div class="chankan-deg"></div>
							</span>
							<span v-else>查看</span>
						</el-button>
					</template>
				</mtable>
			</div>
			<div class="flex justify-end">
				<pagination v-model="pager" @change="getLists" />
			</div>
		</el-card>
		<EdittablePopup v-if="showTable" ref="editRefs" :type="'order_detail'" @success="getLists" @close="onclo" />
		<edit-popup v-if="showEdit" ref="editRef" @success="getLists" @close="showEdit = false" />
		<edit-popupr v-if="showEditr" ref="editRefr" @success="getLists();onNum()" @close="showEditr = false" />
	</div>
</template>

<script lang="ts" setup>
	import {
		adminDelete,
		adminListsorder,
		admincheckActionPermissions
	} from '@/api/inventory/list'
	import mtable from '@/components/table/index.vue'
	import {
		adminlistColumn
	} from '@/api/warehouse/list'
	import {
		usePaging
	} from '@/hooks/usePaging'
	import {
		getCommonFieldDisplay
	} from '@/api/tools/code'
	import EdittablePopup from '@/components/settable/index.vue'
	import feedback from '@/utils/feedback'
	import EditPopup from './edit.vue'
	import EditPopupr from '../list/edit.vue'
	import useAppStore from '@/stores/modules/inventory'
     //<!-- Ecrs单据分布 ——高扬添加-->
    import{useRoute} from "vue-router";
    import useUserStore from '@/stores/modules/user';
    import { orderNotice, scrapOrderNotice,financeOrderNotice } from "@/api/tools/code";
    const userStore1 = useUserStore();
     //<!-- Ecrs单据分布 ——高扬添加-->
    const route = useRoute();
	const userStore = useAppStore()
	const editRef = shallowRef<InstanceType<typeof EditPopup>>()
	const editRefr = shallowRef<InstanceType<typeof EditPopup>>()
	const editRefs = shallowRef<InstanceType<typeof EdittablePopup>>()
	// 表单数据
	const formData = reactive({
		order_no: '',
		type: '',
		delivery_no: '',
		warehouse_id: [],
		outbound_warehouse_id: [],
		start_time: '',
		end_time: '',
	})
	const typeTable = ref('order_detail')
	const showTable = ref(false)
	const date = ref('')
	watch(date, (newValue, oldValue) => {
		formData.start_time = newValue[0]
		formData.end_time = newValue[1]
	})
	const imgData = (val) => {
		var list = []
		for (let i of val) {
			list.push(i.url)
		}
		return list
	}
	const options = reactive({
		listColumn: [] as any[],
		listtype: [{
			title: '入库单',
			id: 10
		},
		{
			title: '调拨单',
			id: 20
		}
		],
		tableTile: [] as any[],
		useJurisdiction: "",
		useJurisdictionr: ''
	})
	const showEdit = ref(false)
	const showEditr = ref(false)
	const {
		pager,
		getLists,
		resetParams,
		resetPage
	} = usePaging({
		fetchFun: adminListsorder,
		params: formData
	})
	const onresetParams = () => {
		resetParams()
		date.value = ''
	}
    // 修复个数不更新的问题
    const onNum = () => {
        orderNotice().then((data: any) => {
            for (let i = 0; i < userStore1.routes?.length; i++) {
                if (userStore1.routes[i].meta.title == "单据详情") {
                    userStore1.routes[i].meta.total = data.total;
                }
            }
        });
          // lqy获取请款单详情数量
          financeOrderNotice().then((data: any) => {
        if (data) {
            for (let i = 0; i < userStore1.routes?.length; i++) {
                if (userStore1.routes[i].meta.title == '财务管理') {
                    if (userStore1.routes[i].children?.length != 0&&userStore1.routes[i].children.find(x=>x.meta.title==='请款单详情')) {
                        userStore1.routes[i].children[userStore1.routes[i].children.findIndex(x=>x.meta.title==='请款单详情')].meta.total = data.total
                    }
                }
            }
        }
    })
        scrapOrderNotice().then((data: any) => {
            if (data) {
                for (let i = 0; i < userStore1.routes?.length; i++) {
                    if (userStore1.routes[i].meta.title == "报废管理") {
                        if (userStore1.routes[i].children?.length != 0) {
                            userStore1.routes[i].children[1].meta.total = data.total;
                        }
                    }
                }
            }
        });
    };

	const handleAdds = async () => {
		showTable.value = true
		await nextTick()
		editRefs.value?.open('add')
	}
	const handleAddr = async () => {
		showEditr.value = true
		await nextTick()
		editRefr.value?.open('add')
	}
	const handleAdd = async (val) => {
		showEdit.value = true
		userStore.ontypeing('调拨单')
		await nextTick()
		editRef.value?.open('add')
	}
	const onclo = () => {
		showTable.value = false
		getOptions()
	}
	const handleEdit = async (data : any) => {
        // console.log(data);
        
		showEdit.value = true
		userStore.ontypeing(data.type_name)
		await nextTick()
		editRef.value?.open('edit')
		editRef.value?.setFormData(data)
	}

	const getOptions = () => {
		getCommonFieldDisplay({
			type: typeTable.value
		}).then((data : any) => {
			options.tableTile = data
		})
		adminlistColumn({
			page_type: 0
		}).then((data : any) => {
			options.listColumn = data
		})
		admincheckActionPermissions().then((data : any) => {
			options.useJurisdiction = data.type20
			options.useJurisdictionr = data.type10
		})
	}

	const tableheight = ref(null)
	const heighting = () => {
		const divH = document.getElementById('headerH').clientHeight
		if (divH == '56') {
			tableheight.value = parseInt(document.documentElement.clientHeight) - 205
		} else {
			tableheight.value = parseInt(document.documentElement.clientHeight) - 180
		}
	}
	// onMounted(() => {
    //     //<!-- Ecrs单据分布 ——高扬添加-->
    //     if(Object.keys(route.query).length != 0){
    //         formData.start_time = route.query.firstDay;
    //         formData.end_time =route.query.lastDay;
    //         formData.type = Number(route.query.type);
    //         date.value =[formData.start_time,formData.end_time];
    //     }
	// 	heighting()
	// 	getLists()
	// 	getOptions()

	// })
    onMounted(() => {
  const q = JSON.parse(sessionStorage.getItem("_q"));
  if (q) {
    formData.start_time = q.firstDay;
    formData.end_time = q.lastDay;
    formData.type = Number(q.type);
    formData.warehouse_id = q.warehouse_id;
    date.value = [formData.start_time, formData.end_time];
  }
  heighting();
  getLists();
  getOptions();
});
onUnmounted(() => {
  sessionStorage.removeItem("_q");
});
</script>
<style>
	.el-table .warning-row {
		--el-table-tr-bg-color: var(--el-color-warning-light-9);
	}

	.el-table .success-row {
		--el-table-tr-bg-color: var(--el-color-success-light-9);
	}

	.mb-\[-16px\] {
		margin-bottom: 0px;
	}

	.el-form-item {
		margin-bottom: 0px;
	}
</style>
<style scoped>
	.chankan {
		position: relative;
	}

	.chankan-deg {
		position: absolute;
		top: -4px;
		right: -6px;
		width: 7px;
		height: 7px;
		background-color: red;
		border-radius: 100%;
	}

	.hong {
		width: 8px;
		height: 8px;
		background-color: red;
		border-radius: 100%;
	}

	::v-deep .el-badge__content.is-dot {
		height: 10px;
		width: 10px;
	}

	.demo-image__error .image-slot {
		font-size: 30px;
	}

	.demo-image__error .image-slot .el-icon {
		font-size: 30px;
	}

	.demo-image__error .el-image {
		width: 100%;
		height: 100px;
	}
</style>